<?php
namespace Admin\Controller;

class IndexController extends BaseController {
    
    /**
     * 后台首页
     */
    public function index(){
        $sql="SELECT c.category,count('a.*') as count FROM mf_articles as a LEFT JOIN mf_categories c on c.id=a.category_id GROUP BY category";
        $pieData=M()->query($sql);
        $sql1="SELECT FROM_UNIXTIME(create_time,'%Y-%m-%d') as time , count(*) as count FROM mf_articles GROUP BY  time ORDER BY time desc LIMIT 30";
        $lineData=M()->query($sql1);
        $this->pieData=$pieData;
        $this->lineData=array_reverse($lineData);
        $this->articleCount=M('articles')->where('status=1')->count();
        $this->commentCount=M('comments')->where('`to`=0')->count();
        $this->messageCount=M('messages')->where('`to`=0')->count();
        /*本月新增数*/
        $month=date("m");
        $this->monthCount=M()->query("SELECT count(*) count FROM mf_articles where FROM_UNIXTIME(create_time,'%Y-%m')=date_format(now(),'%Y-%m') AND status=1")[0]['count'];
        $this->info = array(
            '操作系统'=>PHP_OS,
            '运行环境'=>$_SERVER["SERVER_SOFTWARE"],
            'PHP运行方式'=>php_sapi_name(),
            'ThinkPHP版本'=>THINK_VERSION,
            '上传附件限制'=>ini_get('upload_max_filesize'),
            '执行时间限制'=>ini_get('max_execution_time').'秒',
            '服务器时间'=>date("Y年n月j日 H:i:s"),
            '北京时间'=>gmdate("Y年n月j日 H:i:s",time()+8*3600),
            '服务器域名/IP'=>$_SERVER['SERVER_NAME'].' [ '.gethostbyname($_SERVER['SERVER_NAME']).' ]',
            '剩余空间'=>round((disk_free_space(".")/(1024*1024)),2).'M',
            'register_globals'=>get_cfg_var("register_globals")=="1" ? "ON" : "OFF",
            'magic_quotes_gpc'=>(1===get_magic_quotes_gpc())?'YES':'NO',
            'magic_quotes_runtime'=>(1===get_magic_quotes_runtime())?'YES':'NO',
        );
        /*最近评论*/
        $nearComments=M('comments')->alias('c')->join('__ARTICLES__ a on a.id=c.article_id','LEFT')->field('c.*,a.id as aid,a.title')
        ->where('c.`to`=0')->order('c.create_time desc')->limit(4)->select();
        $this->nearComments=array_reverse($nearComments);
        $this->nearMessages=array_reverse(M('messages')->where('`to`=0')->order('create_time desc')->limit(4)->select());
        if(F('webSet')['qqLogin']==1){
            $this->visitors=M('visitors')->limit(5)->order('login_time desc')->select();
        }
        $this->title='后台首页';
        $this->display();
    }

    /**
     * 站点设置
     */
    public function webSet(){
        if(IS_AJAX){
            F('webSet',I('post.'));
            $this->ajaxReturn(array('status'=>1,'msg'=>'配置完成'));
        }
        $this->title='站点设置';
        $this->display();
    }

    /**
     * 删除缓存
     */
    public function deleteCache(){
        set_time_limit(120);
        if(IS_AJAX){
            $this->delFile(C('DATA_CACHE_PATH'));
            $this->delFile('./Application/Runtime/Cache/Home/');
            $this->delFile('./Application/Runtime/Cache/Admin/');
            $this->delFile('./Application/Runtime/Temp/');
            $this->delFile('./Application/Html/');
            $this->ajaxReturn(array('status'=>1,'msg'=>'删除成功'));
        }
    }

    /**
     * 删除文件夹下的所有文件
     * @param  [string] $dirName [文件夹]
     */
    private function delFile($dirName){
        if(file_exists($dirName) && $handle=opendir($dirName)){
            while(false!==($item = readdir($handle))){
                if($item!= "." && $item != ".."){
                    if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){
                        delFile($dirName.'/'.$item);
                    }else{
                        unlink($dirName.'/'.$item);
                    }
                }
            }
            closedir($handle);
        }
    }

    /**
     * 备份数据库
     */
    public function dbbake(){
        set_time_limit(4*3600*10);
        if(!is_dir('./DB_back')){
            if(!mkdir(iconv("UTF-8", "GBK", './DB_back'),0777,true)){
                //没有创建
                $resdata['status'] = 0;
                $resdata['msg']='创建文件夹失败,请手动创建';
                $this->ajaxReturn($resdata);
            }
        }
        if(C('DB_PWD')!=I('post.password')){
            $this->ajaxReturn(array('status'=>0,'msg'=>'数据库密码错误'));
        }
        $mysqlfile=getcwd()."/DB_back/".C('DB_NAME')."_".date('Y_m_d').".sql";
        $shell="E:/phpstudy/mysql/bin/mysqldump -uroot -p".C('DB_PWD')." ".C('DB_NAME')." >".$mysqlfile;
        exec($shell);
        $this->ajaxReturn(array('status'=>1,'msg'=>'备份成功'));
    }

    /**
     * 菜单管理
     */
    public function menu(){
        $data=I('post.');
        if(IS_AJAX && $data['add']==1){
            /*添加*/
            unset($data['add']);
            if(M('menus')->add($data)){
                $this->ajaxReturn(array('status'=>1,'msg'=>'菜单已保存'));    
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'保存失败'));
            }
        }
        if(IS_AJAX && $data['delete']==1){
            /*删除*/
            if(M('menus')->delete($data['id'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'删除完成'));    
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
            }
        }
        if(IS_AJAX && $data['edit']==1){
            /*修改*/
            if(M('menus')->save(array('id'=>I('post.id'),I('post.field')=>I('post.value')))){
                 $this->ajaxReturn(array('status'=>1,'msg'=>'修改完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'修改失败'));
            }
        }
        if(IS_AJAX && $data['status']==1){
            /*更改状态*/
            $status=M('menus')->field('status')->find(I('post.id'))['status']?0:1;
            if(M('menus')->save(array('id'=>I('post.id'),'status'=>$status))){
                $this->ajaxReturn(array('status'=>1,'msg'=>'修改完成','data'=>$status));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'修改失败'));
            }
        }
        $this->menus=M('menus')->select();
        $this->title='菜单管理';
        $this->display();
    }

    /**
     * 日志文件查看
     */
    function logs(){
        /*获取日志文件*/
        $logPath=RUNTIME_PATH.'Logs/Home/';
        $logdate=I('get.logdate');
        if(!empty($logdate)){
            $log=$logPath.date('y_m_d',strtotime($logdate)).'.log';
        }else{
            $log=$logPath.date('y_m_d').'.log';
        }
        $this->logs=file_get_contents($log);
        $this->title='系统日志';
        $this->display();
    }

}